﻿using System;
using Landpy.CruiseControlNet.ConfigurationSidekick.Resources;
using Landpy.CruiseControlNet.FacadeInterface.ConfigurationModule;

namespace Landpy.CruiseControlNet.ConfigurationSidekick.ConfigTreeModule
{
    class ProjectSecurityHandler : UpdateChildrenNode
    {
        public override void UpdateChildrenNodes(ChildrenNodeContext childrenNodeContext)
        {
            var treeNodeIndentity = this.GetTreeNodeIndentity(childrenNodeContext);
            var treeNodesBuilder = this.GetTreeNodesBuilder(childrenNodeContext.CruiseControl);
            if (treeNodeIndentity.Type == TreeNodeType.ProjectSecurity)
            {
                if (childrenNodeContext.ChangedValueKey == typeof(Permission).Name)
                {
                    var permissionsTreeNode = childrenNodeContext.SelectedNode.Nodes[Resource.TreeNode_Permissions];
                    permissionsTreeNode.Remove();
                    var queryProject = this.ProjectRepository.GetProjectById(childrenNodeContext.CruiseControl,
                                                                             new Guid(treeNodeIndentity.Key));
                    var newPermissionsTreeNode = treeNodesBuilder.BuildPermissionsNode(queryProject, childrenNodeContext.SelectedNode);
                    childrenNodeContext.SelectedNode.Expand();
                    newPermissionsTreeNode.Expand();
                }
            }
            else
            {
                this.Successor.UpdateChildrenNodes(childrenNodeContext);
            }
        }
    }
}
